import { onMounted, onUnmounted } from 'vue'

export function useEChart() {
    let chartInstance = null

    // 初始化图表
    const initChart = (echarts, chartRef, option) => {
        if (!chartRef.value) return
        chartInstance = echarts.init(chartRef.value)
        chartInstance.setOption(option)
        return chartInstance
    }

    // 调整图表大小
    const resizeChart = () => {
        if (chartInstance) {
            chartInstance.resize()
        }
    }

    // 销毁图表
    const disposeChart = () => {
        if (chartInstance) {
            chartInstance.dispose()
            chartInstance = null
        }
    }
    // 这么写不够灵活，不能自己控制什么时候初始化，舍弃这种写法
    // onMounted(() => {
    //     initChart()
    // })

    onUnmounted(() => {
        disposeChart()
    })

    return {
        initChart,
        disposeChart,
        resizeChart, // 添加 resizeChart 到导出列表
        // 相当于function return chartInstance形成一个闭包
        getInstance: () => chartInstance,
    }
}
